unit Heapsort;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, Math;

const
  h=10;
  w=10;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    Panel1: TPanel;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    procedure heapify;
  end;

var
  Form1: TForm1;
  v:array of integer;
  p:array of TPanel;
  N,M,i,t:integer;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.heapify(num:integer);
var a, b, t:integer;
begin
  a:=40000000;
  b:=40000000;
  if (2*num+1 <N) then
    a:=v[2*num+1];
  if (2*num+2 <N) then
    b:=v[2*num+2];
  if (a<=b) and (a<v[num]) then
  begin
    t:=v[num];
    v[num]:=v[2*num+1];
    v[2*num+1]:=t;
    heapify(2*num+1);
  end;
  if (a>b) and (b<v[num]) then
  begin
    t:=v[num];
    v[num]:=v[2*num+2];
    v[2*num+2]:=t;
    heapify(2*num+2);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  N:=StrToInt(Edit1.Text);
  setlength(m, N);
  for i:=0 to N-1 do
    v[i]:=random(1000);
  for i:=N-1 downto 0 do
  begin
    heapify(i);
  end;
  M:=N;
  for i:=0 to M-1 do
  begin
    t:=m[N-1];
    m[N-1]:=m[0];
    m[0]:=t;
    N:=N-1;
    heapify(0);
  end;
  N:=M;
  setlength(p, N);
  for i:=0 to N-1 do
  begin
    p[i]:=TPanel.Create(Form1);
    p[i].Parent:=Form1;
    p[i].Height:=h;
    p[i].Top:=h*(round(log(2, i+1))-1);
    p[i].Width:=w*exp(round(log(2, i+1)*ln(2))/round(log(2, i+2);
    p[i].Left:=w*(exp(round(log(2, i+1)*ln(2))-i mod round(log(2, i+2))
  end;
end;

end.
